﻿using StockWatcher.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StockWatcher
{
    public class AlertManager
    {
        public AlertManager()
        {
            LastAlert = new List<AlertResult>();
        }
        List<AlertResult> LastAlert { get; set; }
        public List<AlertResult> CurrentAlert { get; protected set; }
        public List<AlertResult> CurrentAlertShouldSend { get; protected set; }

        public Dictionary<string, AlertResultForList> CurrentAlertForList { get; protected set; }
        public void SetAlert(Dictionary<string, List<AlertResult>> newAlerts)
        {
            CurrentAlertForList = new Dictionary<string, AlertResultForList>();
            foreach (string code in newAlerts.Keys)
            {
                AlertResultForList alertResultForList = new AlertResultForList();
                alertResultForList.AlertMessages = new List<string>();
                newAlerts[code].ForEach(a =>
                {
                    alertResultForList.AlertLogos += a.AlertLogoChar;
                    alertResultForList.AlertMessages.Add(a.AlertMessage);
                });
                CurrentAlertForList.Add(code, alertResultForList);
            }
            CurrentAlert = new List<AlertResult>();
            foreach (var v in newAlerts.Values)
                CurrentAlert.AddRange(v);
            CurrentAlertShouldSend = CheckAlert(CurrentAlert);
        }

        /// <summary>
        /// 从此次的所有报警中获取已经第一次发出的报警
        /// </summary>
        /// <param name="newAlerts"></param>
        /// <returns></returns>
        private List<AlertResult> CheckAlert(List<AlertResult> newAlerts)
        {
            List<AlertResult> alerts2Save = new List<AlertResult>();
            List<AlertResult> finalAlerts = new List<AlertResult>();
            newAlerts.ForEach(a =>
            {
                alerts2Save.Add(a);
                //如果上次存在这个报警，就不报警了。防止持续发出报警信号时，连续弹窗
                AlertResult oldAlert = LastAlert.Find(b => b.Code == a.Code && b.RuleType == a.RuleType);
                if (oldAlert == null)
                {
                    //add alertlist
                    finalAlerts.Add(a);
                }

            });
            LastAlert = alerts2Save;
            return finalAlerts;
        }

    }
}
